package com.example.imagesharing;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;

import apimanager.RequestMessage;
import apimanager.ResponseMessage;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;
import responsInfo.BaseResponse;
import responsInfo.ErrorResponseInfo;

public class SignUpActivity extends AppCompatActivity implements RequestMessage, ResponseMessage {
    private TextView username;
    private TextView userPwd;
    private TextView userConfirmPwd;
    private Button registerButton;
    private TextView toLogin;
    private ImageView pwdSwitch;
    private ImageView confirmPwdSwitch;
    private boolean pwdVisible=false,confirmPwdVisible=false;
    private final String REGISTER_PATH="user/register";
    private final String REGISTER_REQUEST_MODE="POST";
    public static final String REGISTER_SUCCESS="注册成功";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);
        init();
    }
    private void init(){
        username=findViewById(R.id.et_account);
        userPwd=findViewById(R.id.et_pwd);
        userConfirmPwd=findViewById(R.id.et_pwd2);
        registerButton =findViewById(R.id.btn_register);
        toLogin=findViewById(R.id.tv_sign_up);
        pwdSwitch=findViewById(R.id.iv_pwd_switch);
        confirmPwdSwitch=findViewById(R.id.iv_pwd_switch2);

        setConfirmPwdSwitchListener();
        setPwdSwitchListener();
        setSignUpListener();
        setToLoginListener();
    }

    private void setPwdSwitchListener(){
        pwdSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pwdVisible= !pwdVisible;
                if (pwdVisible){
                    pwdSwitch.setImageResource(R.drawable.y1);
                    userPwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                }
                else {
                    pwdSwitch.setImageResource(R.drawable.x1);
                    userPwd.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD|
                            InputType.TYPE_CLASS_TEXT);
                    userPwd.setTypeface(Typeface.DEFAULT);
                }
            }
        });
    }

    private void setConfirmPwdSwitchListener(){
        confirmPwdSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                confirmPwdVisible= !confirmPwdVisible;
                if (confirmPwdVisible){
                    confirmPwdSwitch.setImageResource(R.drawable.y1);
                    userConfirmPwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                }
                else {
                    confirmPwdSwitch.setImageResource(R.drawable.x1);
                    userConfirmPwd.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD|
                            InputType.TYPE_CLASS_TEXT);
                    userConfirmPwd.setTypeface(Typeface.DEFAULT);
                }
            }
        });
    }

    private void setSignUpListener(){
        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (userConfirmPwd.getText().toString().equals(userPwd.getText().toString())){
                    MediaType mediaType = MediaType.parse("application/json");
                    Gson gson = new GsonBuilder().excludeFieldsWithModifiers(Modifier.STATIC).create();
                    RequestInfo requestInfo=new RequestInfo();
                    requestInfo.password =userPwd.getText().toString();
                    requestInfo.username=username.getText().toString();

                    String requestBody =  gson.toJson(requestInfo);
                    RequestBody body = RequestBody.create(requestBody, mediaType);
                    requestMessage(callback,REGISTER_PATH, REGISTER_REQUEST_MODE, body);
                }else {
                    Snackbar.make(findViewById(R.id.activity_register), "两次输入的密码不一致",
                            Snackbar.LENGTH_SHORT)
                            .show();
                }
            }
        });
    }

    private void setToLoginListener(){
        toLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(SignUpActivity.this,LoginActivity.class);
                startActivity(intent);
            }
        });
    }

    private okhttp3.Callback callback=new Callback() {
        @Override
        public void onFailure(@NonNull okhttp3.Call call, @NonNull IOException e) {

            Snackbar.make(findViewById(R.id.activity_register), "网络请求出错，请检查网络是否异常或稍后再试",
                    Snackbar.LENGTH_SHORT)
                    .show();
        }

        @Override
        public void onResponse(@NonNull okhttp3.Call call, @NonNull Response response) throws IOException {
            responseMessage(call,response);
        }
    };

    @Override
    public void responseMessage(okhttp3.Call call, Response responseMessageFile) throws IOException {
        final String body = responseMessageFile.body().string();
        Gson gson = new Gson();

        if (responseMessageFile.isSuccessful()) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Type jsonType =
                            new TypeToken<BaseResponse<ResponseInfo>>() {
                            }.getType();
                    BaseResponse<SignUpActivity.ResponseInfo> responseInfo =
                            gson.fromJson(body, jsonType);
                    if (responseInfo.getCode()!=200){
                        Snackbar.make(findViewById(R.id.activity_register), responseInfo.getMsg(),
                                Snackbar.LENGTH_SHORT)
                                .show();
                        return;
                    }

                    // skip to the homepage
                    Intent intent = new Intent(SignUpActivity.this, LoginActivity.class);
                    intent.putExtra(REGISTER_SUCCESS,"注册成功");
                    startActivity(intent);
                }
            });
        } else {
            Type jsonType =
                    new TypeToken<ErrorResponseInfo>() {
                    }.getType();
            ErrorResponseInfo responseInfo =
                    gson.fromJson(body, jsonType);
            Snackbar.make(findViewById(R.id.activity_register), responseInfo.getError(),
                    Snackbar.LENGTH_SHORT)
                    .show();
        }
    }

    private class RequestInfo{
        public String username;
        public String password;
    }
    private static class ResponseInfo {}
}
